#include "main.h"
#include <pd_timer.h>
#include <pd_timer_etr.h>
#include <hd_led.h>
#include <hd_oled.h>
#include <delay.h>
#include <hd_oled_protocol_spi.h>
#include <hd_oled_protocol_i2c.h>
#include <stddef.h>
#include <pd_i2c_hd.h>

#define ARRAY_SIZE(x)       sizeof(x) / sizeof(x[0])
#define USE_HARDWARE_SPI    1
#define USE_HARDWARE_I2C    1
uint16_t num;
OLED oled;

extern void SystemClock_Config(void);

void oled_instance(OLED *oled);

int main(void) {
    LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SYSCFG);
    LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

    SystemClock_Config();

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    oled_instance(&oled);

    OLED_printf(&oled, 0, 0, "TIM External CLK");
    OLED_printf(&oled, 0, 16, "Num:");
    OLED_printf(&oled, 0, 32, "Cnt:");
    OLED_refresh(&oled);

    // Set PD2's AF2 as TIM3's external clock source(TIM3_ETR)
    GPIO timerGPIO;
    GPIO_constructor(&timerGPIO, GPIOD, LL_GPIO_PIN_2);
    timerGPIO.Mode = LL_GPIO_MODE_ALTERNATE;
    timerGPIO.Alternate = LL_GPIO_AF_2;

    TimerCh timerCh;
    TimerCh_constructor(&timerCh, &timerGPIO, 1, NULL, 0);

    Timer timer;
    Timer_constructor(&timer, TIM3, 1 - 1, 10 - 1);
    TimerETR timerETR;
    TimerETR_constructor(&timerETR, &timer, &timerCh);

    TimerETR_init(&timerETR, TIM3_IRQn, 2, 2);

    while (1) {
        OLED_printf(&oled, 32, 16, "%6d", num);
        OLED_printf(&oled, 32, 32, "%6d", Timer_getCounter(&timer));
        OLED_refresh(&oled);

        delay_ms(1);
    }
}

void TIM3_IRQHandler(void) {
    if (LL_TIM_IsActiveFlag_UPDATE(TIM3)) {
        LL_TIM_ClearFlag_UPDATE(TIM3);

        num++;
    }
}


void oled_instance(OLED *oled) {
    // I2C gpio init
    static GPIO oledSckGPIO, oledSdaGPIO;
    GPIO_constructor(&oledSckGPIO, GPIOB, LL_GPIO_PIN_10); // I2Cx_SCK
    GPIO_constructor(&oledSdaGPIO, GPIOB, LL_GPIO_PIN_11); // I2Cx_SDA

#ifdef USE_HARDWARE_I2C
    static I2CHardware i2c2;
    I2CHardware_constructor(&i2c2, I2C2, &oledSckGPIO, &oledSdaGPIO);
#elif USE_SIMULATE_I2C
    static I2CSimulate i2c2;
    I2CSimulate_constructor(&i2c2, &oledSckGPIO, &oledSdaGPIO);
#endif
    I2C_init((I2C *)&i2c2);

    // OLED protocol of I2C
    static OLEDProtocolI2C oledProtocolI2c;
    OLEDProtocolI2C_constructor(&oledProtocolI2c, (I2C *)&i2c2);

    // OLED font instance.
    static OLEDFont oledFont;
    OLEDFont_contructor(&oledFont, NULL);

    // OLED instance of 4-PIN(I2C)
    OLED_constructor(oled, (OLEDProtocol *)&oledProtocolI2c, &oledFont);

    OLED_init(oled);

    OLED_clear(oled);
    OLED_refresh(oled);
}
